<?php

namespace app\services;

use plugin\admin\app\model\Coupon;
use plugin\admin\app\model\GoodsCategory;
use plugin\admin\app\model\GoodsCategoryRelation;
use plugin\admin\app\model\UserCoupon;

class CouponService
{
    public static function giftCoupon()
    {
        return Coupon::select(['id'])->where('only_for_gift', 1)->first();
    }

    public static function register()
    {
        $coupons = Coupon::select(['id', 'full', 'reduce', 'goods_category_ids', 'type', 'expiry_days', 'total_count', 'receive_count'])->where('register_send', 1)->get()->toArray();

        if (count($coupons) == 0) {
            return [];
        }

        $couponIds = array_column($coupons, 'id');

        $userCoupons = UserCoupon::whereIn('coupon_id', $couponIds)->where('user_id', get_user_id())->get()->toArray();

        foreach ($userCoupons as $userCoupon) {
            $coupons = array_filter($coupons, function ($coupon) use ($userCoupon) {
                return $coupon['id'] != $userCoupon['coupon_id'];
            });
        }

        return array_values($coupons);
    }

    public static function square($couponIds = [])
    {
        $query = Coupon::select(['id', 'full', 'reduce', 'goods_category_ids', 'type', 'expiry_days', 'total_count', 'receive_count']);
        if (count($couponIds) > 0) {
            $query->whereIn('id', $couponIds);
        }
        $coupons = $query->get()->toArray();
        $categoryIds = explode(',', join(',', array_filter(array_column($coupons, 'goods_category_ids'))));

        $categories = GoodsCategory::whereIn('id', $categoryIds)->get()->toArray();
        $categories = array_combine(
            array_column($categories, 'id'),
            array_values($categories)
        );

        $userCoupons = UserCoupon::where('user_id', get_user_id())->get()->toArray();
        $userCoupons = array_combine(
            array_column($userCoupons, 'coupon_id'),
            array_values($userCoupons)
        );

        foreach ($coupons as $key=>$coupon) {
            $coupon['type_text'] = Coupon::getTypeText($coupon['type']);
            Coupon::getRangeText($coupon, $categories);

            $coupon['start_time'] = date('Y-m-d H:i:s');
            $coupon['end_time'] = date('Y-m-d H:i:s', strtotime('+' . $coupon['expiry_days'] . ' days'));

            [$coupon['status'], $coupon['status_text']] = UserCoupon::getStatus($coupon, $userCoupons[$coupon['id']] ?? null);

            $coupons[$key] = $coupon;

        }

        return $coupons;
    }

    public static function goodsCoupons($goodsId)
    {
        $relation = GoodsCategoryRelation::where('goods_id', $goodsId)->get()->toArray();

        if (count($relation) == 0) {
            return [];
        }

        $categoryIds = array_column($relation, 'category_id');
        $coupons = Coupon::all()->toArray();

        $couponIds = [];

        foreach ($coupons as $coupon) {

            if ($coupon['goods_category_ids']) {
                $cids = explode(',', $coupon['goods_category_ids']);

                if (count(array_intersect($cids, $categoryIds)) > 0) {
                    $couponIds[] = $coupon['id'];
                }
            } else {
                $couponIds[] = $coupon['id'];
            }
        }

        print_r($couponIds);

        return self::square($couponIds);

    }

    public static function list($status = 0, $price = 0)
    {
        $query = UserCoupon::where('user_id', get_user_id());

        if ($status == 0) {
            $query->where('expiry_time', '>', time())->whereNull('use_time');
        } elseif ($status == 1) {
            $query->whereNotNull('use_time');
        } else {
            $query->where('expiry_time', '<=', time());
        }

        $coupons = $query->get()->toArray();

        $data = [];

        foreach ($coupons as $coupon) {
            $couponData = json_decode($coupon['data'], true);
            unset($couponData['count']);
            $couponData['id'] = $coupon['id'];

            $couponData['is_expiry'] = intval($coupon['expiry_time']  <= time());
            $couponData['is_use'] = intval(is_null($coupon['use_time']));
            $couponData['start_time'] = date('Y-m-d', $coupon['created_time']);
            $couponData['end_time'] = date('Y-m-d', $coupon['expiry_time']);

            if ($price > 0 && $couponData['full'] > $price) {
                continue;
            }

            $data[] = $couponData;
        }

        return $data;
    }

}